package pers.mobian.springforth;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import pers.mobian.springfirst.firstTest.User;

import java.lang.reflect.Field;

/**
 * @Date 2021/7/10 18:38
 * @Created mobian
 * @Description
 */
//@Component
public class MyBeanProcessor implements BeanPostProcessor {

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		System.out.println("BeforeInitialization");
		System.out.println(bean + "" + beanName);
		return null;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		System.out.println("AfterInitialization");
		System.out.println(bean + "----" + beanName);

		Class<?> aClass = bean.getClass();

		// 遍历所有的属性
		for (Field field : aClass.getDeclaredFields()) {

			// 获取成员变量上使用的name注解
			Name annotation = field.getAnnotation(Name.class);

			// 不为null，则表示获取到了对应的name注解
			if(annotation != null) {

				// 获取对应注解的值
				String value = annotation.value();

				// 开启私有属性的修改
				field.setAccessible(true);

				try {
					field.set(bean,value);
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}
		}

		return null;
	}
}
